package com.example.naodian.task;

import cn.hutool.json.JSONUtil;
import com.example.naodian.websocket.WebSocketServer;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

@Component
public class MyTask {
    private final WebClient webClient = WebClient.create();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private ScheduledFuture<?> scheduledFuture;


    //开始
    public void startTask() {
        System.out.println("任务已启动");
        if (scheduledFuture == null || scheduledFuture.isCancelled()) {
            scheduledFuture = scheduler.scheduleAtFixedRate(this::sendRequest, 0, 5, TimeUnit.SECONDS);
        }
    }

    //停止
    public void stopTask() {
        System.out.println("任务已停止");
        if (scheduledFuture != null && !scheduledFuture.isCancelled()) {
            scheduledFuture.cancel(false);
        }
    }

    private void sendRequest() {
        String url = "http://localhost:8088//eeg/eeg-data-block/list"; // 示例 API
        try {
            // 发送 GET 请求并处理响应
            Mono<String> responseMono = webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(String.class);

            String response = responseMono.block(); // 阻塞等待响应
            if (JSONUtil.isNull(response)) {
                return;
            }
            // 通过WebSocket发送数据到前端
            WebSocketServer.broadcast(response);
        } catch (Exception e) {
            System.err.println("发送请求错误: " + e.getMessage());
        }
    }
}
